#include <stdio.h>
#include "rtc.h"
#include "mem.h"
#include "uart.h"
#include "main.h"
#include "funcBlock.h"
#include "funcBlock_CLOCK.h"

// Anzahl der Minuten an einem Tag
const uint16_t cDayMinutes = 24 * 60;

struct fb_CLOCK
{
	uint8_t type;
	function_t func;
	uint8_t UP;
	uint8_t DOWN;
	uint8_t SEL;
	uint8_t Q16;
};

void function_fb_CLOCK(struct funcBlock_t *_fb)
{
	struct datetime_t dt;
	uint16_t minute; // anz. Minuten seit Sonntag 00:00 Uhr
	struct fb_CLOCK *fb = (struct fb_CLOCK*)_fb;

	if (getState(fb->SEL == 0) || (fb->SEL == 0xFF))
	{
		if (rtc_get_datetime(&dt) == 0)
		{
			minute = (dt.weekday * cDayMinutes) + (dt.hour * 60) + dt.min;
			setBusValue_16b(fb->Q16, minute);
		}
	}
	else
		setBusValue_16b(fb->Q16, 0);
}

struct funcBlock_t* get_fb_CLOCK(uint8_t UP, uint8_t DOWN, uint8_t SEL, uint8_t Q16)
{
	struct fb_CLOCK *fb = NULL;

	if (Q16 < NUM_16BIT_BUS)
	{	
		fb = (struct fb_CLOCK*)getMem(sizeof(struct fb_CLOCK));
		if (fb != NULL)
		{
			//uart_puts("CLOCK\n");
			fb->type = FB_TYPE_CLOCK;
			fb->func = function_fb_CLOCK;
			fb->UP = UP;
			fb->DOWN = DOWN;
			fb->SEL = SEL;
			fb->Q16	= Q16;
		}
	}
	return (struct funcBlock_t*)fb;
}
